package main

import (
	"alarm_service/common/logger"
	"alarm_service/injector"
	"context"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	ij, err := injector.BuildInjector()
	if err != nil {
		panic(err)
	}

	srv := &http.Server{
		Addr:    ":8081",
		Handler: ij.Engine,
	}
	//  监听HTTP连接
	go func() {
		// 服务连接
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Errorf("listen: %s", err)
			panic("http server closed")
		}

	}()

	// 监听TCP连接
	go func() {
		listener, err := net.Listen("tcp", ":8080")
		if err != nil {
			panic("Error starting TCP server")
			os.Exit(1)
		}
		defer listener.Close()
		logger.Info("[TCP] server started on 8080")
		for {
			// 接受客户端连接
			conn, err := listener.Accept()
			if err != nil {
				logger.Errorf("accepting connection Error: %v", err)
				continue
			}
			// 处理客户端连接
			//go handleConnection(conn)
			go ij.TcpRouter.HandleTcpConnection(conn)
		}
	}()

	go func() {
		logger.Info("[task] Starting Running as Cron Mode")
		go ij.BatchProcessor.Init()
		quit := make(chan os.Signal)
		signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
		<-quit
		logger.Global().Infof("[task] starting shutdown cronjob runner")
		go ij.BatchProcessor.Shutdown()
		time.Sleep(20 * time.Second)
		logger.Global().Infof("[task] exited cronjob runner")
		os.Exit(0)
	}()

	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	logger.Info("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		logger.Error("Server Shutdown: %v", err)
	}
	logger.Info("Server exiting")
}

// todo error check
// todo 代码优化
